/**
 * Created by Michael on 20-1-14.
 */

var feedId = 40053;
var datastreamId = "winddir";
var myImage = "#graphImage";
var graph;
var points;
var labels;
var angleIncrement = 3;
var baseUrl = "https://api.xively.com/v2/feeds/40053/";
var lastdata;

$(document).ready(function () {
    console.log("Ready");
    getData();
    getDataPoints();
    console.log($('#dataname').html());
    console.log("Done");

    $('#valueTable .curval').each(function () {
        console.log($(this).html());
    });

    $('#intervalSelection').change(function () {
        getData();
        getDataPoints();
    });

    rotateSun();
	
    $('#startdate').text();
    $('#enddate').text();
    $('#startdate').change(function () {
        getHistoryData();
    });
    $('#enddate').change(function () {
        console.log($('#startdate').empty());
        getHistoryData();
    });

    $("#sunCanvas").click(function () {
        angleIncrement++;
    });

    $(window).resize(respondCanvas);
    function respondCanvas()
    {
        var c = $('#myChart');
        var ctx = $("#myChart").get(0).getContext("2d");

        c.get(0).width = window.innerWidth*0.985;
        c.get(0).height = (window.innerWidth*0.985)/2;
        ctx.clearRect(0, 0, c.get(0).width, c.get(0).height);
        makeGraph(lastdata);

        var s = $('#sunCanvas');
        var sctx = $('#sunCanvas').get(0).getContext("2d");

        s.get(0).width = window.innerWidth * 0.2;
        s.get(0).height = window.innerWidth * 0.2;

        rotateSun();
    }

    respondCanvas();

    $('#dataname')(function ()
    {
        getData();
        getDataPoints();
    });

    $.ajax(
        {
            url:"https://api.xively.com/v2/feeds/40053",
            type: 'GET',
            dataType: 'json',
            success:function(data){parseWeatherStationData(data)},
            error:function() { alert('boo'); },
            beforeSend: setHeader
        });
});

function getData()
{
    console.log("getData called");
    var url = baseUrl;
    console.log($('#dataname').val());
    console.log(url);

    $.ajax(
        {
            url: url + "datastreams/" + $('#dataname').html()+".json",
            type: 'GET',
            dataType: 'json',
            success: function (data) { parseJSONData(data) },
            error: function () {  },
            beforeSend: setHeader
        });
}

function getHistoryData() {
    console.log("getHistoryData called");
    var url = baseUrl;
    console.log($('#startdate').val().toString());
    console.log(url + "datastreams/" + $('#dataname').html() + ".json" + "?start=" + $('#startdate').val().toString() + "&end=" + $('#enddate').val().toString());
    console.log($('#enddate').val().toString());

    $.ajax(
        {
            url: url + "datastreams/" + $('#dataname').html() + ".json" + "?start=" + $('#startdate').val().toString() + "&end=" + $('#enddate').val().toString() + "&interval=43200",
            type: 'GET',
            dataType: 'json',
            success: function (data) { parseJSONDataPoints(data) },
            error: function () { alert('Either start date field or end date field is empty!'); },
            beforeSend: setHeader
        });
}


function getDataPoints() {
    console.log("getData called");
    var url = baseUrl;

    $.ajax(
        {
            url: url + "datastreams/" + $('#dataname').html() + ".json" + "?interval=6000&duration=" + $('#intervalSelection').val(),
            type: 'GET',
            dataType: 'json',
            success: function (data) { parseJSONDataPoints(data) },
            error: function () {  },
            beforeSend: setHeader
        });
}

function parseWeatherStationData(data)
{
    $("#description")[0].innerText = data["description"];
}


function rotateSun() {
    var canvas = document.getElementById('sunCanvas');
    var ctx = canvas.getContext('2d');
    var img = new Image();
    var ang = 0; //angle

    var fps = 1000 / 60; //number of frames per sec
    img.onload = function () { //on image load do the following stuff
        canvas.width = this.width << 1; //double the canvas width
        canvas.height = this.height << 1; //double the canvas height
        var cache = this; //cache the local copy of image element for future reference
        setInterval(function () {
            ctx.save(); //saves the state of canvas
            ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
            ctx.translate(cache.width, cache.height); //let's translate
            ctx.rotate(Math.PI / 180 * (ang += angleIncrement)); //increment the angle and rotate the image
            ctx.drawImage(img, -cache.width, -cache.height, cache.width*2, cache.height*2); //draw the image ;)
            ctx.restore(); //restore the state of canvas
        }, fps);
    };

    img.src = "http://www.parochieputtesintniklaas.be/afbeeldingen/logo's%20en%206op6/zonnetje.png"; //img
}



function parseJSONData(data)
{
    console.log(data);

    var unit = data["unit"]["symbol"];

    $("#curval")[0].innerText = data["current_value"] + " " + unit;
    $("#minval")[0].innerText = data["min_value"] + " " + unit;
    $("#maxval")[0].innerText = data["max_value"] + " " + unit;

    //makeGraph(points);
}



function parseJSONDataPoints(data) {
    console.log(data);
    var datapoints = data["datapoints"];
    console.log("datapoints: " + datapoints.length);
    points = Array(datapoints.length);
    labels = Array(datapoints.length);

    for (var i = 0; i < datapoints.length; i++) {
        points[i] = parseFloat(datapoints[i]["value"]);
        labels[i] = "";
    }

    console.log(points);

    makeGraph(points);
}

function setHeader(xhr)
{
    xhr.setRequestHeader('X-PachubeApiKey', 'P_btPeh4FcS-eBfr4NheLke2QvSSAKxmZ0hRQ2taTGlxYz0g');
}

function makeGraph(data)
{
    //Get context with jQuery - using jQuery's .get() method.
    var ctx = $("#myChart").get(0).getContext("2d");
    var fillcolor;
    var strokecolor;

    console.log("draw graph: ", data);
    lastdata = data;

    if ($('#dataname').html() == "airpressure")
    {
        fillcolor = "rgba(64,64,255,0.5)";
        strokecolor = "rgb(0,0,255)";
    }
    else if($('#dataname').html() == "hum")
    {
        fillcolor = "rgba(40,199,230,0.5)";
        strokecolor = "rgb(0,0,255)";
    }
    else if ($('#dataname').html() == "rainrate") {
        fillcolor = "rgba(6,76,182,0.5)";
        strokecolor = "rgb(0,0,255)";
    }
    else if ($('#dataname').html() == "temp") {
        fillcolor = "rgba(247,158,41,0.5)";
        strokecolor = "rgb(255,0,0)";
    }
    else if ($('#dataname').html() == "windspeed") {
        fillcolor = "rgba(30,247,103,0.5)";
        strokecolor = "rgb(0,255,0)";
    }
    else if ($('#dataname').html() == "winddir") {
        fillcolor = "rgba(30,247,45,0.5)";
        strokecolor = "rgb(0,255,0)";
    }

    var d = {
        labels: labels,
        datasets: [
            {
                fillColor: fillcolor,
                strokeColor: strokecolor,
                data: data
            }
        ]
    }

    graph = new Chart(ctx).Line(d, { pointDot: false});
}
